package com.adcc.ags.cgw.healthcheck;

import com.adcc.ags.cgw.entity.mq.MQInfo;
import com.adcc.ags.cgw.entity.mq.MQState;
import com.adcc.ags.cgw.managed.uplink.UplinkForward;
import com.adcc.utility.log.Log;
import com.codahale.metrics.health.HealthCheck;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.base.Strings;
import com.google.common.collect.Maps;

import java.util.HashMap;
import java.util.Map;

/**
 * 上行状态监控
 */
public class GWHealthCheck extends HealthCheck {

    @Override
    protected Result check() throws Exception {
        try {
            Map<String,Object> map = Maps.newHashMap();
            Map<String,String> mq = Maps.newHashMap();

            // 设置网关主机名称
            map.put("host",UplinkForward.getInstance().getHost());

            // 设置网关名称
            map.put("name",UplinkForward.getInstance().getName());

            // 获取MQ运行状态
            MQInfo mqInfo = UplinkForward.getInstance().getMQInfo();
            String strHost = mqInfo.getHost();
            mq.put("host", Strings.nullToEmpty(strHost));
            int intPort = mqInfo.getPort();
            mq.put("port",(intPort > 0) ? String.valueOf(intPort) : "");
            String strQM = mqInfo.getQm();
            mq.put("qm",Strings.nullToEmpty(strQM));
            String strChannel = mqInfo.getChannel();
            mq.put("channel",Strings.nullToEmpty(strChannel));
            MQState mqState = mqInfo.getState();
            mq.put("state", mqState.toString());
            map.put("mq",mq);

            // 获取网关运行模式
            map.put("mode",UplinkForward.getInstance().getMode());

            if (mqState == MQState.CONNECTED) {
                return Result.healthy(new ObjectMapper().writeValueAsString(map));
            } else {
                return Result.unhealthy(new ObjectMapper().writeValueAsString(map));
            }
        } catch (Exception ex) {
            Log.error(GWHealthCheck.class.getName(), "check() error", ex);
            return Result.unhealthy(ex.toString());
        }
    }
}
